<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\admin\model\AdminUserModel;
use app\admin\validate\AdminUserValidate;
use think\Controller;
use think\Request;

class Login extends Controller
{
    /*
     * 登录表单
     */
    public function index()
    {
        return $this->fetch();
    }

    /*
     * 登录
     */
    public function save(Request $request)
    {
        $data     = $request->param();
        $validate = new AdminUserValidate();
        if (!$validate->check($data)) {
            return ['code' => 0, 'msg' => $validate->getError()];
        }
        $db     = new AdminUserModel();
        $fields = 'user_id, user_name, password, last_login, action_list, last_login,suppliers_id,ec_salt';
        $info   = $db->where('user_name', $data['username'])->field($fields)->find();
        if (empty($info)) {
            return ['code' => 0, 'msg' => '账号不存在'];
        }
        if (empty($info['ec_salt'])) {
            if ($info['password'] != md5($data['password'])) {
                return ['code' => 0, 'msg' => '账号或密码错误'];
            }
        } else {
            if ($info['password'] != md5(md5($data['password']) . $info['ec_salt'])) {
                return ['code' => 0, 'msg' => '账号或密码错误'];
            }
        }
        if (empty($info['ec_salt'])) {
//            设置盐  重置密码
            $ec_salt      = rand(1, 9999);
            $new_possword = md5(md5($data['password']) . $ec_salt);
            $db->where('user_id', $info['user_id'])->setField('password', $new_possword);
        }
//        更新时间和ip
        $db->where('user_id', $info['user_id'])->setField('last_login', time());
        $db->where('user_id', $info['user_id'])->setField('last_ip', $request->ip());
//        存session
        session('admin_id', $info['user_id']);
        session('admin_user_name', $info['user_name']);
        session('admin_last_login', $info['last_login']);

//        记入登录日志
        $log               = new AdminLog();
        $arr['log_time']   = time();
        $arr['user_id']    = $info['user_id'];
        $arr['log_info']   = '管理员登录';
        $arr['ip_address'] = $request->ip();
        $log->save($arr);
        return ['code' => 1, 'msg' => '登录成功'];
    }
    /*
     * 退出
     */
    public function logout()
    {
        session('admin_id', null);
        session('admin_user_name', null);
        session('admin_last_login', null);
        return ['code' => 1, 'msg' => '退出成功'];
    }

}
